package com.vonchenchen.process;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Surface;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * Created by lidede on 2021/6/29.
 */
public class RendererClient {

    private static final String TAG = "Renderer_Client";

    private static RendererClient sInst = null;
    private RendererClient(){};

    private OnConnectListener mOnConnectListener = null;

    public static RendererClient getInstance(){
        if(sInst == null){
            synchronized (RendererClient.class){
                if(sInst == null){
                    sInst = new RendererClient();
                }
            }
        }
        return sInst;
    }

    IRendererInterface mRemoteRender;

    private ServiceConnection conn = new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected");
            mRemoteRender = IRendererInterface.Stub.asInterface(service);
            if(mOnConnectListener != null){
                mOnConnectListener.OnConnected();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected");
            if(mOnConnectListener != null){
                mOnConnectListener.OnDisConnect();
            }
        }
    };

    public int connect(Context context, OnConnectListener listener){

        mOnConnectListener = listener;
        context.bindService(new Intent(context, RendererProcessService.class), conn, BIND_AUTO_CREATE);

        return 0;
    }

    public void initSurface(Surface surface){

        Log.i(TAG, "Init1");
        if(mRemoteRender == null) {

            return ;
        }

        Log.i(TAG, "Init2");
        try {
            mRemoteRender.Init(surface);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public interface OnConnectListener{
        void OnConnected();
        void OnDisConnect();
    }
}
